package com.company.JUC.ThreadPool.ThreadPoolExecutorTest;

import com.company.JUC.ThreadPool.RejectedExecutionHandlerImpl;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.*;


public class ThreadPoolExecutorTest {


    public static void main(String[] args) throws InterruptedException {

           /*声明拒绝策略*/
           RejectedExecutionHandlerImpl rejectedExecutionHandler = new RejectedExecutionHandlerImpl();
           /*默认线程工厂*/
            ThreadFactory threadFactory = Executors.defaultThreadFactory();
            /*Spring框架提供的*/
            CustomizableThreadFactory customizableThreadFactory = new CustomizableThreadFactory(
                    "springThread-pool");

            /*Google guava 工具类提供的*/
            ThreadFactory guavaThreadFactory  = new ThreadFactoryBuilder().setNameFormat("retryClient-pool-").build();


            /*创建线程*/
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    2,
                    4,
                    10,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(2),
                    /*threadFactory*/ customizableThreadFactory  /*guavaThreadFactory*/ ,
                    rejectedExecutionHandler);
            /*开始监视 线程池*/
        MyMonitorThread myMonitorThread = new MyMonitorThread(threadPoolExecutor, 1);
        new Thread(myMonitorThread).start();

            /*提交10个线程给线程池*/
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPoolExecutor.execute(()-> {
                System.out.println(Thread.currentThread().getName()+" start : " + finalI);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" end " + finalI);
            });
        }

        Thread.sleep(30000);
        //shut down the pool
        threadPoolExecutor.shutdown();
        //shut down the monitor thread
        Thread.sleep(5000);
        myMonitorThread.shutdown();
    }


}